<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- <el-button type="primary" @click="goAddpage">添加商品</el-button> -->
          <el-button type="primary" @click="addFormDialog = true">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- table表格区域 -->
      <el-table :data="goodslist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column label="商品价格(元)" prop="goods_price" width="95px"></el-table-column>
        <el-table-column label="商品重量" prop="goods_weight" width="70px"></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="140px">
          <template slot-scope="scope">
            {{scope.row.add_time | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditFormDialog(scope.row.goods_id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeById(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" background>
      </el-pagination>
    </el-card>
    <!-- 添加商品的对话框 -->
    <el-dialog title="添加商品" :visible.sync="addFormDialog" @close="close">
      <el-form :model="addForm" ref="addFormRef" :rules="editFormRules">
        <el-form-item prop="goods_name" label="商品名称" label-width="100px">
          <el-input v-model="addForm.goods_name" />
        </el-form-item>
        <el-form-item prop="goods_price" label="商品价格" label-width="100px">
          <el-input type="number" v-model="addForm.goods_price" />
        </el-form-item>
        <el-form-item prop="goods_number" label="商品数量" label-width="100px">
          <el-input type="number" v-model="addForm.goods_number" />
        </el-form-item>
        <el-form-item prop="goods_weight" label="商品重量" label-width="100px">
          <el-input type="number" v-model="addForm.goods_weight" />
        </el-form-item>
        <el-form-item label="商品图片" label-width="100px">
           <!-- action 表示图片要上传到的后台API地址 -->
            <el-upload :action="uploadURL" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addFormDialog = false">取消</el-button>
        <el-button type="primary" @click="addGoods">确定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑商品的对话框 -->
    <el-dialog title="编辑商品" :visible.sync="editFormDialog">
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item prop="goods_name" label="商品名称" label-width="100px">
          <el-input v-model="editForm.goods_name" />
        </el-form-item>
        <el-form-item prop="goods_price" label="商品价格" label-width="100px">
          <el-input v-model="editForm.goods_price" />
        </el-form-item>
        <el-form-item prop="goods_number" label="商品数量" label-width="100px">
          <el-input v-model="editForm.goods_number" />
        </el-form-item>
        <el-form-item prop="goods_weight" label="商品重量" label-width="100px">
          <el-input v-model="editForm.goods_weight" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editFormDialog = false">取消</el-button>
        <el-button type="primary" @click="editGoods">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表
      goodslist: [],
      // 总数据条数
      total: 0,
      // 添加商品的表单数据对象
      addForm: {
        // 上传图片的数组
        pics: []
      },
      // 控制添加商品对话框的显示与隐藏
      addFormDialog: false,
      // 上传图片的URL地址
      uploadURL: 'http://shiyansong.cn:8888/api/private/v1/upload',
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      editFormDialog: false, // 控制编辑商品对话框的显示与隐藏
      // 编辑表单的数据对象
      editForm: {},
      editFormRules: {
        goods_name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量不能为空', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 根据分页获取对应的商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败！')
      }

      this.$message.success('获取商品列表成功！')
      console.log(res.data)
      this.goodslist = res.data.goods
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    async removeById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }

      const { data: res } = await this.$http.delete(`goods/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }

      this.$message.success('删除成功！')
      this.getGoodsList()
    },
    goAddpage() {
      this.$router.push('/goods/add')
    },
    // 处理移除图片的操作
    handleRemove(file) {
      // console.log(file)
      // 1. 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2. 从 pics 数组中，找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      // 3. 调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      // console.log(response)
      // 1. 拼接得到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      // 2. 将图片信息对象，push 到pics数组中
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    },
    // 添加商品
    async addGoods() {
      const { data: res } = await this.$http.post('/goods', this.addForm)
      if (res.meta.status !== 201) {
        this.$message.error('添加商品信息失败')
      } else {
        // 1.重新渲染数据
        this.getGoodsList()
        // 2.给出提示
        this.$message.success('添加商品信息成功')
        // 3.让添加商品对话框隐藏
        this.addFormDialog = false
        // 4.将上传图片的数组清空
        this.addForm.pics = []
      }
    },
    close() {
      this.$refs.addFormRef.resetFields()
      this.addForm.pics = []
    },
    // 显示编辑商品的对话框
    async showEditFormDialog(id) {
      const { data: res } = await this.$http.get('/goods/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('商品信息查询失败')
      } else {
        this.editForm = res.data
        this.editFormDialog = true
      }
    },
    // 确定编辑商品
    editGoods() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('表单格式不正确')
        } else {
          const { data: res } = await this.$http.put('/goods/' + this.editForm.goods_id, this.editForm)
          if (res.meta.status !== 200) {
            this.$message.error('编辑商品失败')
          } else {
            // 1. 重新渲染商品列表
            this.getGoodsList()
            // 2. 给出提示
            this.$message.success('编辑商品成功')
            // 3. 让编辑表单隐藏
            this.editFormDialog = false
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
